﻿using Stylet;
using System;
using System.Collections.Generic;
using System.Windows.Interop;
using System.Windows;
using System.Windows.Threading;
using System.Linq;
using Common.Model;
using Common.Models;
using Common.Utility.AJ;
using Common.Utility;
using Masuit.Tools;
using System.Windows.Controls;
using Microsoft.EntityFrameworkCore;
using Common.EF.Controllers;
using Common;

namespace AWSV2.ViewModels
{
    public class ICCardDetailViewModel : AnnotationValidationScreen<ICCard>
    {
        private string _title;
        public string Title
        {
            get => _title;
            set => SetAndNotify(ref _title, value);
        }

        private AJErrorInfoDialogParams _errorInfo;
        public AJErrorInfoDialogParams ErrorInfo
        {
            get => _errorInfo;
            set => SetAndNotify(ref _errorInfo, value);
        }

        private bool _addMode;
        public bool AddMode
        {
            get => _addMode;
            set => SetAndNotify(ref _addMode, value);
        }

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        private ICCard _form;
        public override ICCard Form
        {
            get => _form;
            set => SetAndNotify(ref _form, value);
        }

        public List<Customer> CustomerOptions { get; set; }

        public List<Car> CarOptions { get; set; }

        public List<Goods> GoodsOptions { get; set; }

        public BindableCollection<GoodsSpec> GoodsSpecOptions { get; set; }


        public ICCardDetailViewModel(ICCard form = null, string currentReadCardId = null)
        {
            ErrorInfo = new AJErrorInfoDialogParams();
            GoodsSpecOptions = new BindableCollection<GoodsSpec>();
            AddMode = form == null;
            Title = AddMode
                ? I18NService.Translate(LangKeys.新增, I18NService.Translate(LangKeys.IC卡))
                : I18NService.Translate(LangKeys.编辑_0_, form.CardId);
            _form = new ICCard();
            if (form != null)
            {
                AJUtil.CopyPropertyValues(_form, form);
            }
        }

        protected override async void OnViewLoaded()
        {
            Loading = true;

            using var db = AJDatabaseService.GetDbContext();
            var mapper = AJAutoMapperService.Instance().Mapper;

            var customerPage = await db.Customers.AsNoTracking().ToListAsync();

            CustomerOptions = mapper.Map<List<Common.EF.Tables.Customer>, List<Customer>>(customerPage);

            var carPage = await db.Cars.AsNoTracking().ToListAsync();

            CarOptions = mapper.Map<List<Common.EF.Tables.Car>, List<Car>>(carPage);

            var goodsPage = await db.Goods.Include(p => p.SpecList).AsNoTracking().ToListAsync();

            GoodsOptions = mapper.Map<List<Common.EF.Tables.Goods>, List<Goods>>(goodsPage);

            if (goodsPage.Count > 0)
            {
                GoodsSpecOptions.Clear();
                var specSource = mapper.Map<List<Common.EF.Tables.GoodsSpec>, List<GoodsSpec>>(goodsPage
                    .FirstOrDefault().SpecList.ToList());
                GoodsSpecOptions.AddRange(specSource);
            }

            Loading = false;
        }

        private bool _canCommit;
        public bool CanCommit
        {
            get
            {
                _canCommit = !Loading;
                return _canCommit;
            }
            set => SetAndNotify(ref _canCommit, value);
        }
        public async void Commit()
        {
            if (!ValidateModel())
            {
                ErrorInfo.Show(string.Join("\r\n", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString())));
                return;
            }

            Loading = true;
            try
            {
                using var ctrl = new ICCardController();
                var result = await ctrl.Save(AJAutoMapperService.Instance()
                    .Mapper.Map<ICCard, Common.EF.Tables.ICCard>(_form));

                RequestClose(true);
            }
            catch (Exception e)
            {
                ErrorInfo.Show(e.Message);
            }
            finally
            {
                Loading = false;
            }
        }


        public void GoodsChangedHandle(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
            if (sender is ComboBox && e.AddedItems?.Count > 0)
            {
                var goods = e.AddedItems[0] as Goods;
                GoodsSpecOptions.Clear();
                GoodsSpecOptions.AddRange(goods.SpecList);
            }
        }
    }
}
